import { useEffect, useState } from 'react'

type API<T, P> = (param: P) => Promise<T>

export default function useFetch<T, P>(api: API<T, P>, _params: P) {
  const [param, setParam] = useState(_params)
  const [list, setList] = useState<T>()
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (loading) {
      return
    }
    
    let timer = setTimeout(() => {
      getList()
    }, 250)
    return () => {
      clearTimeout(timer)
    }
  }, [param])

  function getList() {
    api(param).then(res => {
      setList(res)
      setLoading(false)
      setError('')
    }).catch(err => {
      setLoading(false)
      setError(err)
    })
  }

  useEffect(() => {
    loading && getList()
  }, [loading])

  return { 
    param, 
    setParam,
    list, 
    error, 
    loading, 
    setLoading 
  }
}